// activity/pages/kan_price/index.js
const apis = require('../../../utils/api').apis;
const url = require('../../../utils/getUrl');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    successMask: true, //砍价成功弹窗
    failMask: true, //砍价失败弹窗
    successFriendMask: true, //好友砍价成功弹窗


    dataArr: [],

    curriculumId: 0, //课程id
    price: 0, //价钱
    classification: 0, //课程类型
    percentage: 0, //进度条
    //倒计时数据
    countdown: {
      day: '',
      hour: '',
      minute: '',
      second: ''
    },
    timer: null, //定时器

    isShare: false, //是否是分享卡片进来的
    userActivityId: 0,
    success: false, //好友砍价成功
    cancel: false,

    num: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    // 获取课程信息
    this.data.curriculumId = options.curriculumId;
    this.data.price = options.price;
    this.data.classification = options.classification;
    //是否从分享卡片进来
    if (options.code == '1007') {
      console.log('ddd', '好友')

      this.setData({
        isShare: true,
        userActivityId: options.userActivityId
      })
      this.getUserData()

    } else {
      this.getData()

    }
    // 判断是否砍价成功
    // if(((this.data.dataArr.currentPrice*1000)-(this.data.dataArr.bargainingPrice*1000))/1000==0){
    //   this.setData({
    //     successMask:false
    //   })
    // }
    console.log(this.data.isShare)



  },
  //获取用户活动信息
  getData() {
    wx.showLoading({
      title: '加载中'
    })
    apis.bargainingQueryBargainingByUser({
      curriculumId: Number(this.data.curriculumId)
    }).then(res => {
      if (res.data != null) {
        this.setData({
          dataArr: res.data
        })
        let bargainingMoney = parseInt(this.data.dataArr.curriculumPrice - this.data.dataArr.currentPrice); //砍得价格
        this.data.percentage = (bargainingMoney / parseInt(this.data.dataArr.curriculumPrice - this.data.dataArr.bargainingPrice)) * 100;
        this.setData({
          percentage: this.data.percentage
        })
        var endTime = new Date(this.data.dataArr.endTime.replace(/-/g,'/')).getTime();
        var nowTime = new Date().getTime();

        this.startCountdown(nowTime, endTime)
        console.log('用户', this.data.cancel, this.data.isShare, this.data.success, this.data.dataArr)
      }
      wx.hideLoading()
    })
  },
  // 好友进来获取活动信息
  getUserData() {
    wx.showLoading({
      title: '加载中'
    })
    apis.bargainingQueryBargainingByUser({
      userActivityId: this.data.userActivityId
    }).then(res => {
      console.log('朋友',res)
      if (res.data != null) {
        this.setData({
          dataArr: res.data
        })
        console.log('好友', this.data.cancel, this.data.isShare, this.data.success, this.data.dataArr)

        let bargainingMoney = parseInt(this.data.dataArr.curriculumPrice - this.data.dataArr.currentPrice); //砍得价格
        this.data.percentage = (bargainingMoney / parseInt(this.data.dataArr.curriculumPrice - this.data.dataArr.bargainingPrice)) * 100;

        this.setData({
          percentage: this.data.percentage,
          success: res.data.isBargaining == 'bargaining' ? true : false
        })
        var endTime = new Date(this.data.dataArr.endTime.replace(/-/g,'/')).getTime();
        var nowTime = new Date().getTime();
        this.startCountdown(nowTime, endTime)
        console.log('endTime',this.data.dataArr.endTime,endTime)
        console.log(bargainingMoney, parseInt(this.data.dataArr.curriculumPrice - this.data.dataArr.bargainingPrice), this.data.percentage)
        wx.hideLoading()

      }
    })
  },
  // 直接购买
  gobuy() {
    console.log('购买',this.data.curriculumId,this.data.classification)
    wx.navigateTo({
      url: '/curriculum/pages/purchase/index?id=' + this.data.curriculumId + '&classification=' + this.data.classification,
    })
  },
  // 砍一刀
  bargainingBargaining() {
    let token = wx.getStorageSync('Xd_Token');
    if (token == null || token == undefined || token == '') {
      url.getUrl()
      console.log('存储路由',wx.getStorageSync('Router'))
      wx.navigateTo({
        url: '/login/pages/login/index?userActivityId='+this.data.userActivityId,
      })
    }else{
      if (this.data.num == 0) {
        this.setData({
          num: 1
        })
        apis.bargainingBargaining({
          id: this.data.userActivityId
        }).then(res => {
          if (!res.success) {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            return
          }
          this.setData({
            success: true,
            // successFriendMask:false
          })
          console.log('砍价', res)
          this.getUserData()
        })
      } else {
        return
      }
    }

  },
  // 立即学习
  goDetail() {
    wx.navigateTo({
      url: '/curriculum/pages/course/index?id=' + this.data.dataArr.curriculumId,
    })
  },

  // 关闭弹窗
  close() {
    this.setData({
      successMask: true,
      failMask: true
    })
  },
  // 调用消息通知
  shareRemind() {
    wx.requestSubscribeMessage({
      tmplIds: ['ZXHbWmR2rrqFZWbgt6q4kF_COAsF1r6P0Nsnu9EwyUk'],
      success(res) {
        console.log(res)
      }
    })
  },
  // 下拉事件
  onRefresh() {
    if (this.data.isShare) {
      console.log('好友刷新')
      this.getUserData()
    } else {
      console.log('用户刷新')
      this.getData()
    }
    wx.stopPullDownRefresh()
  },
  // 计算倒计时
  startCountdown: function (serverTime, endTime) {
    var that = this;
    serverTime = new Date(serverTime);
    var millisecond = endTime - serverTime;
    console.log(millisecond)
    that.data.timer = setInterval(function () {
      console.log('循环中');
      millisecond -= 1000;
      if (millisecond <= 0) {
        clearInterval(that.data.timer);
        that.setData({
          countdown: {
            day: '00',
            hour: '00',
            minute: '00',
            second: '00'
          },
          cancel: true,
          failMask: false,
        });
        return;
      }
      that.transformRemainTime(millisecond);
    }, 1000);
  },
  // 剩余时间(毫秒)处理转换时间
  transformRemainTime: function (millisecond) {
    var that = this;
    var countdownObj = that.data.countdown;
    // 秒数
    var seconds = Math.floor(millisecond / 1000);
    // 天数
    countdownObj.day = that.formatTime(Math.floor(seconds / 3600 / 24));
    // 小时
    countdownObj.hour = that.formatTime(Math.floor(seconds / 3600 % 24));
    // 分钟
    countdownObj.minute = that.formatTime(Math.floor(seconds / 60 % 60));
    // 秒
    countdownObj.second = that.formatTime(Math.floor(seconds % 60));
    that.setData({
      countdown: countdownObj
    });
    // console.log(this.data.countdown)
  },
  //格式化时间为2位
  formatTime: function (time) {
    if (time < 10)
      return '0' + time;
    return time;
  },
  goDownLoad() {
    console.log('下载')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /** 
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let token = wx.getStorageSync('Xd_Token');
    // // 获取课程信息
    // this.data.curriculumId = options.curriculumId;
    // this.data.price = options.price;
    // this.data.classification = options.classification;
    // //是否从分享卡片进来
    // if (options.code == '1007') {
    //   console.log('ddd','好友')
    //   this.setData({
    //     isShare: true,
    //     userActivityId: options.userActivityId
    //   })
    //   if (token == null||token==undefined||token=='') {
    //     url.getUrl()
    //     wx.navigateTo({
    //       url: '/login/pages/login/index',
    //     })
    //   }
    //   this.getUserData()
    //   console.log(this.data.userActivityId)
    // } else {
    //   this.getData()

    // }
    // if(((this.data.dataArr.currentPrice*1000)-(this.data.dataArr.bargainingPrice*1000))/1000){
    //   this.setData({
    //     successMask:false
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let curriculumId = res.target.dataset.curriculumid
    let userActivityId = res.target.dataset.useractivityid
    console.log(res.target.dataset, curriculumId, userActivityId)
    return {
      title: '快来帮我砍一刀！',
      path: '/activity/pages/kan_price/index?code=1007&curriculumId=' + curriculumId + '&userActivityId=' + userActivityId
      // path: '/activity/pages/kan_price/index?code=1007&curriculumId=' + this.data.curriculumId + '&price=' + this.data.price + '&classification=' + this.data.classification + '&userActivityId=' + this.data.dataArr.id
    }
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
  }
})